//
//  PlayViewController.m
//  WayToHome
//
//  Created by A-01 on 2020/6/22.
//  Copyright © 2020 A-01. All rights reserved.
//

#import "PlayViewController.h"
#import "ColorCollectionViewCell.h"
#import "DoneViewController.h"

@interface PlayViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,DoneViewControllerDelegate>

@property (nonatomic, weak)UILabel * titleLab;
@property (nonatomic, weak)UICollectionView * collectionView;
@property (nonatomic, strong)NSArray * colorArray;
@property (nonatomic, strong)NSTimer * timer;
@property (nonatomic, weak)UIToolbar *toolbar;
@property (nonatomic, weak)UILabel * countLabel;
@property (nonatomic, assign)NSInteger state;//0:显示 1:隐藏
@property (nonatomic, assign)NSInteger count;//点击次数

@end

@implementation PlayViewController

//倒计时总的秒数
static NSInteger  secondsCountDown = 5;
static int second = 0;
static int min = 0;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
}


- (void)viewWillAppear:(BOOL)animated{
    
    self.state = 0;
    secondsCountDown = 6;
    self.count = 0;
    second = 0;
    min = 0;
    self.titleLab.text = @"";
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //样式
    toolbar.barStyle = UIBarStyleBlack;//半透明
    //透明度
    toolbar.backgroundColor = ZRBlackColor;
    toolbar.alpha = 0.7f;
    
    self.toolbar = toolbar;
    [self.navigationController.view addSubview:self.toolbar];
    
    
    UILabel * countLabel = [[UILabel alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    countLabel.textColor = ZRWhiteColor;
    countLabel.textAlignment = NSTextAlignmentCenter;
    countLabel.font = [UIFont boldSystemFontOfSize:32];
    
    self.countLabel = countLabel;
    
    [self.navigationController.view addSubview:self.countLabel];
}

- (void)viewDidDisappear:(BOOL)animated{
    
    [self.timer invalidate];
}

//定时器的方法
- (void)countDownAction{
    
    if (self.state == 0) {
        
        secondsCountDown --;
        if(secondsCountDown > 1){
            
            self.countLabel.text = [NSString stringWithFormat:@"%ld",(long)secondsCountDown];
        }else if(secondsCountDown == 1){
            
            self.countLabel.text = @"Start";
        }else if(secondsCountDown == 0){
            
            self.state = 1;
            [self.timer invalidate];
            [self.countLabel removeFromSuperview];
            [self.toolbar removeFromSuperview];
            [self.collectionView reloadData];
            self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
        }
    }else{

        second = second + 1;
        if (second == 60) {
            second = 0;
            min ++;
        }
        if (min == 60) {
            
            DoneViewController * doneVc = [DoneViewController new];
            doneVc.type = 0;
            doneVc.score = @"";
            doneVc.delegate = self;
            [self.navigationController pushViewController:doneVc animated:YES];
        }
        
        self.titleLab.text = [NSString stringWithFormat:@"%2d:%.2d",min,second];
    }
    
}


- (void)setupUI{
                
    UILabel * titleLab = [UILabel new];
            
    titleLab.textColor = [UIColor colorWithHexString:@"0AB966"];
    titleLab.font = [UIFont boldSystemFontOfSize:24];
    titleLab.textAlignment = NSTextAlignmentCenter;
                
    self.titleLab = titleLab;
                
    [self.view addSubview:self.titleLab];
    
    
    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
    layout.itemSize =CGSizeMake(42, 42);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
        //设置collectionView滚动方向
    //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        //2.初始化collectionView
    UICollectionView * collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake((kScreenW - 420) / 2, 70 , 420, self.view.height - 75) collectionViewLayout:layout];
        
    collectionView.backgroundColor = [UIColor clearColor];
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.showsVerticalScrollIndicator = NO;
        //3.注册collectionViewCell
    //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [collectionView registerClass:[ColorCollectionViewCell class] forCellWithReuseIdentifier:@"ColorCollectionViewCell"];
        //4.设置代理
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    self.collectionView = collectionView;
    
    [self.view addSubview:self.collectionView];
    
    [self addImageView];
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.state == 1) {
       
        int res = [self.resultArray[self.count] intValue];
        if (res == indexPath.row) {
            
            if (self.count == self.resultArray.count - 1) {
                DoneViewController * doneVc = [DoneViewController new];
                doneVc.type = 1;
                doneVc.score = self.titleLab.text;
                doneVc.index = self.level;
                doneVc.delegate = self;
                [self.navigationController pushViewController:doneVc animated:YES];
                NSArray * oldArr = [DEF_GET_OBJECT(self.level) componentsSeparatedByString:@":"];
                NSArray * newArr = [self.titleLab.text componentsSeparatedByString:@":"];
                if (oldArr) {
                    
                    if ([newArr.firstObject intValue] < [oldArr.firstObject intValue]) {
                        
                        DEF_SET_OBJECT(self.titleLab.text, self.level);
                    }else if ([newArr.firstObject intValue] == [oldArr.firstObject intValue]){
                        
                        if ([newArr.lastObject intValue] < [oldArr.lastObject intValue]) {
                            
                            DEF_SET_OBJECT(self.titleLab.text, self.level);
                        }
                    }
                }else{
                    
                    DEF_SET_OBJECT(self.titleLab.text, self.level);
                }
            
            }
            ColorCollectionViewCell * cell = (ColorCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
            int color = arc4random() % self.colorArray.count;
            NSString * colorStr = self.colorArray[color];
            cell.backImageView.backgroundColor = [UIColor colorWithHexString:colorStr];
        }else{
            
            DoneViewController * doneVc = [DoneViewController new];
            doneVc.type = 0;
            doneVc.score = @"";
            doneVc.index = self.level;
            doneVc.delegate = self;
            [self.navigationController pushViewController:doneVc animated:YES];
        }
        
        self.count ++;
    }
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return 50;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    ColorCollectionViewCell * cell = (ColorCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (cell == nil) {

        cell = (ColorCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"ColorCollectionViewCell" forIndexPath:indexPath];
    }
    //设置数据
    if (self.state == 0) {
        
        if ([self.resultArray containsObject:@(indexPath.row)]) {
            
            int color = arc4random() % self.colorArray.count;
            NSString * colorStr = self.colorArray[color];
            cell.backImageView.backgroundColor = [UIColor colorWithHexString:colorStr];
        }else{
            
            cell.backImageView.backgroundColor = [UIColor colorWithHexString:@"0AB966"];
        }
        
    }else{
        
        cell.backImageView.backgroundColor = [UIColor colorWithHexString:@"0AB966"];
    }
    
    if (indexPath.row == self.homeIndex) {
            
        cell.backImageView.image = [UIImage imageNamed:@"roof"];
    }else{
        
        cell.backImageView.image = [UIImage imageNamed:@""];
    }
    
    return cell;
}


- (void)backWithType:(NSString *_Nullable)type WithResArr:(NSArray *)array WithHome:(int)home{
    
    if ([type isEqualToString:@"back"]) {
        
        [self.collectionView reloadData];
    }else{
        
        self.level = [NSString stringWithFormat:@"%d",[self.level intValue] + 1];
        self.resultArray = array;
        self.homeIndex = home;
        [self.collectionView reloadData];
    }
}

- (void)viewDidLayoutSubviews{

    [super viewDidLayoutSubviews];

    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(20);
    }];
}


#define Start_X          50.0f      // 第一个按钮的X坐标
#define Start_Y          60.0f     // 第一个按钮的Y坐标
#define Height_Space     12.0f     // 竖间距
#define Button_Width    38.0f    // 宽
-(void)addImageView
{
    for (int i = 0 ; i < 5; i++) {

        NSString *img;
        if (i % 2==0) {
            
            img = @"flower";
        }else{
            
            img = @"leaf";
        }
        // 圆角按钮
        UIImageView *imageView = [UIImageView new];
        imageView.image = [UIImage imageNamed:img];
        imageView.frame = CGRectMake(Start_X, i * (Button_Width + Height_Space)+Start_Y, Button_Width, Button_Width);
         
        [self.view addSubview:imageView];
    }
}


- (NSArray *)colorArray{
    
    if (!_colorArray) {
        
        _colorArray = @[@"0089FF",@"F2D230",@"FF8233",@"A966FE",@"FFC5AD",@"F390D2"];
    }
    
    return _colorArray;
}

@end
